/*
 * Copyright 2008 Andrej Herich
 * 
 * http://azetclient.yw.sk/
 * http://azetclient.googlecode.com/
 * 
 * This file is part of AzetClient.
 * 
 * AzetClient is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * AzetClient is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with AzetClient.  If not, see <http://www.gnu.org/licenses/>.
 */

package sk.yw.azetclient.gui;

import java.awt.Color;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;
import org.apache.log4j.Logger;
import sk.yw.azetclient.Main;
import sk.yw.azetclient.azet.AzetMessageBean;
import sk.yw.azetclient.model.Buddy;
import sk.yw.azetclient.model.Message;
import sk.yw.azetclient.model.MessageBean;
import sk.yw.azetclient.model.MessageThread;
import sk.yw.azetclient.model.MessageThreadEvent;
import sk.yw.azetclient.model.MessageThreadListener;

/**
 *
 * @author  error216
 */
public class ConversationPanel extends javax.swing.JPanel
        implements MessageThreadListener {
    
    private static final long serialVersionUID = 2565874029l;
    
    private static final Logger logger =
            Logger.getLogger(ConversationPanel.class);
    
    private static final Style DEFAULT_STYLE = StyleContext
            .getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
    
    private static final DateFormat MESSAGE_DATE_FORMAT =
            new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
    
    private ConversationFrame frame;
    private Buddy user;
    private Buddy buddy;
    private MessageThread thread;
    private StyledDocument conversationDocument;
    private StyledDocument inputDocument;
    private int lastMessageOffset;
    
    /** Creates new form MessagThreadPanel */
    public ConversationPanel(ConversationFrame frame, Buddy user, Buddy buddy,
            MessageThread thread) {
        if (frame == null)
            throw new IllegalArgumentException("Null pointer in frame");
        if (user == null)
            throw new IllegalArgumentException("Null pointer in user");
        if (buddy == null)
            throw new IllegalArgumentException("Null pointer in buddy");
        if (thread == null)
            throw new IllegalArgumentException("Null pointer in thread");
        
        this.frame = frame;
        this.user = user;
        this.buddy = buddy;
        this.thread = thread;
        
        initComponents();
        
        conversationDocument = conversationTextPane.getStyledDocument();
        Style userMessageStyle =
                conversationDocument.addStyle("userMessage", DEFAULT_STYLE);
        StyleConstants.setForeground(userMessageStyle, Color.GRAY);
        
        inputDocument = inputTextPane.getStyledDocument();
        
        if (thread.getLastMessage() != null
                && user.equals(thread.getLastMessage().getReceiver())) {
            Main.getMainFrame().getConversationFocusQueue().add(this);
        }
        
        synchronized (conversationDocument) {
            thread.addMessageThreadListener(this);
            
            for (Message message : thread.getMessages()) {
                addMessage(message);
            }
        }
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSplitPane1 = new javax.swing.JSplitPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        conversationTextPane = new javax.swing.JTextPane();
        jScrollPane2 = new javax.swing.JScrollPane();
        inputTextPane = new javax.swing.JTextPane();

        jSplitPane1.setDividerLocation(230);
        jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);

        conversationTextPane.setEditable(false);
        jScrollPane1.setViewportView(conversationTextPane);

        jSplitPane1.setTopComponent(jScrollPane1);

        inputTextPane.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                inputTextPaneKeyPressed(evt);
            }
        });
        jScrollPane2.setViewportView(inputTextPane);

        jSplitPane1.setRightComponent(jScrollPane2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents

    private void inputTextPaneKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_inputTextPaneKeyPressed
        if (evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) {
            inputTextPane.setEnabled(false);
            
            final MessageBean bean;
            if (thread.isEmpty()) {
                frame.setSelectedTabTitle(inputTextPane.getText());
                
                bean = new AzetMessageBean();
                bean.setSender(user);
                bean.setReceiver(buddy);
            } else {
                bean = thread.getLastMessage().createReplyBean();
            }
            
            try {
                bean.setContent(
                        inputDocument.getText(0, inputDocument.getLength()));
            } catch (BadLocationException ex) {
                logger.error("Unable to get message text from input text pane.", ex);
            }
            
            try {
                inputDocument.remove(0, inputDocument.getLength());
            } catch (BadLocationException ex) {
                logger.error("Unable to remove message text from input text pane.", ex);
            }
            
            try {
                inputDocument.insertString(0,
                        Main.getText("conversationPanel.waitingForReply"),
                        DEFAULT_STYLE);
            } catch (BadLocationException ex) {
                logger.error("Unable to insert 'waiting for reply' message to input text pane", ex);
            }
            
            
            bean.setSendTime(new Date());
            thread.addMessage(bean);
            final Message message = thread.getLastMessage();
            
            Main.getMainFrame().getConversationFocusQueue().requestNextFocus();
            
            (new Thread() {
                @Override
                public void run() {
                    Main.getMainFrame()
                            .sendMessage(message);
                }
            }).start();
        }
    }//GEN-LAST:event_inputTextPaneKeyPressed
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextPane conversationTextPane;
    private javax.swing.JTextPane inputTextPane;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSplitPane jSplitPane1;
    // End of variables declaration//GEN-END:variables
    
    private void addMessage(Message message) {
        StringBuilder builder = new StringBuilder();
        builder.append('(');
        builder.append(MESSAGE_DATE_FORMAT.format(message.getSendTime()));
        builder.append(')');
        builder.append(' ');
        builder.append(message.getContent());
        builder.append('\n');
        
        Style style;
        if (user.equals(message.getSender())) {
            style = conversationDocument.getStyle("userMessage");
        } else {
            style = DEFAULT_STYLE;
        }
        
        lastMessageOffset = conversationDocument.getLength();
        
        try {
            conversationDocument.insertString(
                    lastMessageOffset,
                    builder.toString(),
                    style);
        } catch (BadLocationException ex) {
            logger.error("Unable to add message to conversation text pane.", ex);
        }
        
        if (user.equals(message.getReceiver())) {
            try {
                inputDocument.remove(0, inputDocument.getLength());
            } catch (BadLocationException ex) {
                logger.error("Unable to remove 'waiting for reply' message.", ex);
            }
            inputTextPane.setEnabled(true);
        }
    }

    public void messageAdded(final MessageThreadEvent e) {
        if (user.equals(e.getMessage().getReceiver())) {
            Main.getMainFrame().getConversationFocusQueue().add(this);
        } else {
            Main.getMainFrame().getConversationFocusQueue().remove(this);
        }
        
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                synchronized (conversationDocument) {
                    addMessage(e.getMessage());
                }
            }
        });
    }

    public void messageChanged(final MessageThreadEvent e) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                try {
                    conversationDocument.remove(lastMessageOffset,
                            conversationDocument.getLength() - lastMessageOffset);
                    addMessage(e.getMessage());
                } catch (BadLocationException ex) {
                    logger.error("Unable to remove message form text pane.", ex);
                }
            }
        }); 
    }
    
    public void setMessageThreadName(String name) {
        thread.setName(name);
    }
    
    public void requestFocusOnInputTextPane() {
        inputTextPane.requestFocus();
    }

    public ConversationFrame getFrame() {
        return frame;
    }
}
